import { defineConfig } from 'rollup';
import fs from 'node:fs';
import typescript from 'rollup-plugin-typescript2';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import { terser } from 'rollup-plugin-terser';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import postcss from 'rollup-plugin-postcss';
import alias from '@rollup/plugin-alias';
import del from 'rollup-plugin-delete';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import json from '@rollup/plugin-json';
import dts from 'rollup-plugin-dts';

const __dirname = fileURLToPath(new URL('.', import.meta.url));
// console.log(path.resolve(__dirname, 'src'))
const pkg = JSON.parse(
  fs.readFileSync(path.resolve(__dirname, './package.json'), 'utf-8'),
);

export default defineConfig((command) => {
  return [
    {
      input: './src/index.ts',
      output: [
        {
          format: 'es',
          dir: 'dist/es',
          preserveModules: true, // 保留模块结构
          // preserveModulesRoot: 'src/*', // 从哪个目录开始保留文件夹结构
          sourcemap: false,
        },
      ],
      external: (id) => {
        const dependencies = Object.keys(
          { ...pkg.devDependencies, ...pkg.dependencies } || {},
        );
        // 将 `dependencies` 的模块和特定的 OpenLayers 模块都标记为外部
        return dependencies.includes(id) || id.startsWith('ol/');
      },
      plugins: [
        // alias({
        //   entries: [{ find: '@', replacement: path.resolve(__dirname, 'src') }],
        // }),
        vue(), // Vue 文件处理必须在前
        vueJsx(), // Vue JSX 支持
        resolve(), // 解析 Node.js 模块
        commonjs(), // 支持 CommonJS 模块
        postcss({
          extensions: ['.css', '.scss'],
          extract: true,
          inject: true,
          modules: true,
          use: ['sass'],
        }),
        json(),
        typescript({
          check: false,
          tsconfigOverride: {
            compilerOptions: {
              declaration: true,
              declarationDir: 'dist/types',
            },
            exclude: ['**/__tests__', '**/*.test.ts'],
          },
          include: ['./global.d.ts'],
          useTsconfigDeclarationDir: true,
        }),
        terser(),
        del({ targets: 'dist/*' }),
      ],
    },
    // {
    //   input: './types/src/index.d.ts',
    //   output: {
    //     dir: path.resolve(__dirname, 'dist/types'), // 这里使用 dir 来保持文件夹结构
    //     format: 'esm',
    //   },
    //   plugins: [
    //     dts()
    //   ]
    // }
  ];
});
